import { defineStore } from 'pinia'
import { accountGetLogin, getUserInfoById, getUserMenus } from '@/services/modules/login'
import { TOKEN } from '@/global/storage'
import { localCache } from '@/utils/Cache'
import type { IAcount } from '@/types/login'
import { mapAddRouter, mapMenuAuthority } from '@/utils/map-menu'
import router from '@/router'
import useMainStore from './main'
import { ElNotification } from 'element-plus'
interface isLoginState {
  token: string
  userInfo: any
  userMenus: any[]
  menuAuthor: any[]
  // load: boolean
}
const useLoginStore = defineStore('Login', {
  state: (): isLoginState => {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      menuAuthor: []
      // load: true
    }
  },
  actions: {
    // 登录的请求
    async getAccountLogin(account: IAcount) {
      // 账号登录, 获取token等信息
      const loginInfo = await accountGetLogin(account)
      this.token = loginInfo.data.token
      const id = loginInfo.data.id

      // 把token存储到本地存储上面防止用户刷新消失
      localCache.setCache(TOKEN, this.token)
      // 获取用户信息
      const userInfoResult = await getUserInfoById(id)
      this.userInfo = userInfoResult.data
      //  根据用户角色id获取不同的菜单权限
      const userMenusResult = await getUserMenus(this.userInfo.role.id)
      this.userMenus = userMenusResult.data
      // 持久性存储
      localCache.setCache('userInfo', userInfoResult.data)
      localCache.setCache('userMenus', userMenusResult.data)
      // 把菜单传进转换工具
      const routes = mapAddRouter(this.userMenus)
      // 动态添加路由
      routes.forEach((route) => {
        // main ： 要添加进去的位置
        router.addRoute('main', route)
      })
      // 获取部门列表
      const mainStore = useMainStore()
      mainStore.fetchDepartmentList()
      // 菜单权限
      const menuAuthor = mapMenuAuthority(userMenusResult.data)
      this.menuAuthor = menuAuthor
      // 跳转路由
      router.push('/main')
      ElNotification({
        title: 'Success',
        message: '欢迎登录',
        type: 'success'
      })
    },
    // 用户刷新动态添加的路由会消失掉 持久性存储
    loginAddRouter() {
      // 用户进行刷新默认加载数据
      const token = localCache.getCache(TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus
        // 获取部门列表
        const mainStore = useMainStore()
        mainStore.fetchDepartmentList()
        // 菜单权限
        const menuAuthor = mapMenuAuthority(userMenus)
        this.menuAuthor = menuAuthor
        const routes = mapAddRouter(userMenus)
        // 动态添加路由
        routes.forEach((route) => {
          // main ： 要添加进去的位置
          router.addRoute('main', route)
        })
      }
    }
  },
  getters: {}
})

export default useLoginStore
